package com.mrsad.view;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JPanel;

import com.mrsad.ctrl.Controller;

public class MainView {
	private JPanel view;
	private Controller controller;
	private JButton[][] jbs = new JButton[7][2];
	private JButton jbUndo;
	private JButton jbTurnOnAll,jbTurnOffAll;//update 3
	public MainView() {
		
		controller = new Controller();
		
		view = new JPanel();
		view.setLayout(new BorderLayout());
		JPanel topView = new JPanel(); //update 4
		JPanel upperView = new JPanel();
		upperView.setLayout(new GridLayout(7,3));
		topView.setLayout(new GridLayout(1,2)); //update 5
		for(int i=0;i<7;i++) {
			ButtonListener listener = new ButtonListener(i);
			upperView.add(controller.getLightViews()[i]);
			upperView.add(jbs[i][0] = new JButton("开"));
			upperView.add(jbs[i][1] = new JButton("关"));
			jbs[i][0].addActionListener(listener);
			jbs[i][1].addActionListener(listener);
		}

		topView.add(jbTurnOnAll = new JButton("全开"));//update 6
		topView.add(jbTurnOffAll = new JButton("全关"));//update 7
		view.add("North",topView);
		view.add("Center", upperView);
		view.add("South", jbUndo = new JButton("撤销"));
		
		TurnAllListener turnAllListener = new TurnAllListener();//update 8
		jbTurnOnAll.addActionListener(turnAllListener);//update 9
		jbTurnOffAll.addActionListener(turnAllListener);//update 10
		
		jbUndo.addActionListener(new UndoButtonListener());
	}
	public class UndoButtonListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			if(e.getSource() == jbUndo) {
				controller.getRc().undo();
			}			
		}		
	}
	public class TurnAllListener implements ActionListener{//update 11

		@Override
		public void actionPerformed(ActionEvent e) {
			if(e.getSource() == jbTurnOnAll) {
				controller.turnOnAll();
			}else if(e.getSource() == jbTurnOffAll) {
				controller.turnOffAll();
			}		
		}		
	}
	
	public class ButtonListener implements ActionListener{
		private int i;		
		public ButtonListener(int i) {			
			this.i = i;
		}
		@Override
		public void actionPerformed(ActionEvent e) {
			JButton jb = (JButton)e.getSource();
			if(jb == jbs[i][0]) {
				controller.getRc().onButtonWasPushed(i);;
			}else if(jb == jbs[i][1]) {
				controller.getRc().offButtonWasPushed(i);;
			}			
		}		
	}
	
	public JPanel getView() {
		return view;
	}
}
